package org.example.JVM.ByteCode.Handler;

import org.example.JVM.ByteCode.Type.ClassFile;
import org.example.JVM.ByteCode.Type.CpInfo;
import org.example.JVM.ByteCode.Type.U1;
import org.example.JVM.ByteCode.Type.U2;

import java.nio.ByteBuffer;

/**
 * @description:常量池解析器
 * @author: farprt
 * @create: 2022-11-13 16:08
 **/
public class ConstantPoolHandler implements BaseByteCodeHandler {

    @Override
    public int order() {
        return 2;
    }

    @Override
    public void read(ByteBuffer codeBuf, ClassFile classFile) throws Exception {
        //获取常量池计数器的值
        U2 cpLen = new U2(codeBuf.get(), codeBuf.get());
        classFile.setConstant_pool_count(cpLen);
        //常量池中常量总数
        //常量相#0为预留，指向#0表示不指向常量池任何一项
        int cpInfoLength = cpLen.toInt() - 1;
        classFile.setConstant_pool(new CpInfo[cpInfoLength]);
        //解释所有常量
        for (int i = 0; i < cpInfoLength; i++) {
            U1 tag = new U1(codeBuf.get());
            CpInfo cpInfo = CpInfo.newCpInfo(tag);
            cpInfo.read(codeBuf);
            System.out.println("#" + (i + 1) + ":" + cpInfo);
            classFile.getConstant_pool()[i] = cpInfo;
        }

    }
}